package me.luger.project.picc.service.picc;

import com.alibaba.fastjson.JSONObject;
import me.luger.core.commom.util.*;
import me.luger.project.picc.entity.*;
import me.luger.project.picc.entity.picc.PolicyResult;
import me.luger.project.picc.service.InsuranceService;
import me.luger.project.picc.service.LearnHealthService;
import me.luger.project.picc.service.SatisfyQuestionService;
import org.apache.commons.collections.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by a on 2017/4/27.
 */
@Service
public class PiccService {
    private static final Logger piccLogger = LoggerFactory.getLogger("piccServiceFile-logger");

    //保单校验接口
    private static final String PICC_CHECK_POLICY_URL = "http://10.136.5.214:9080/CustomerContno";

    //检验openId是否关注picc公众号
    private static final String PICC_CHECK_IS_FOLLOW_URL = "http://10.136.5.214:9080/CustomerToken";

    private static final String PICC_GET_TICKET_URL = "http://10.136.5.214:9080/CustomerTicket";

    //客户满意度有奖调查交互接口
    private static final String PICC_SATIFY_QUESTION_URL = "http://10.136.5.214:9080/CustomerHappy";

    /**
     * 学点健康知识吧交互接口
     */
    private static final String PICC_LEARN_HEALTH_URL = "http://10.136.5.214:9080/CustomerStudy";

    /**
     * 投保有奖交互接口
     */
    private static final String PICC_INSURANCE_URL = "http://10.136.5.214:9080/CustomerMoney";

    /**
     * 我和保单有个约会
     */
    private static final String PICC_PICC_METTING_URL = "http://10.136.5.214:9080/CustomerDate";

    @Autowired
    private SatisfyQuestionService satisfyQuestionService;
    @Autowired
    private InsuranceService insuranceService;
    @Autowired
    private LearnHealthService learnHealthService;

    @Autowired
    private Environment env;

    /**
     * 调用人保接口判断保单状态
     * @param openId
     * @param userName
     * @param pid
     * @return
     */
    public PolicyResult checkPolicyResult(String openId, String userName, String pid){
        PolicyResult policyResult = new PolicyResult();

        if(env.getProperty("spring.profiles.active").equals("dev")){
            policyResult.setDateRight(true);
            policyResult.setExist(true);
            policyResult.setNewRet(true);
            policyResult.setNormal(true);
            policyResult.setSelf(true);
            policyResult.setOverOneYear(true);
        }else{
            Map<String,Object> params = new HashMap<String, Object>();
            if(StringUtil.isBlank(openId)){
                openId = "1";
            }
            params.put("openId",openId);
            params.put("pid",pid);
            try {
                params.put("userName", URLEncoder.encode(userName,"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                LogUtil.errorLog(e,"encode userName error");
            }
            String ret = HttpClientUtil.doGet(PICC_CHECK_POLICY_URL,params);

            policyResult = JsonUtil.parse(ret,PolicyResult.class);

//            policyResult.setDateRight(true);
//            policyResult.setExist(true);
//            policyResult.setNewRet(true);
//            policyResult.setNormal(true);
//            policyResult.setSelf(true);
//            policyResult.setPeriodPay(true);
//            policyResult.setOverOneYear(true);
        }

        return policyResult;
    }

    public boolean checkIsFollowPicc(String openId){
        Map<String,Object> params = new HashMap<String, Object>();
        params.put("openId",openId);

        try{
            String ret = HttpClientUtil.doGet(PICC_CHECK_IS_FOLLOW_URL,params);
            Map<String,Object> logMap = new HashedMap();
            logMap.put("method","checkIsFollowPicc");
            logMap.put("openId",openId);
            logMap.put("ret",ret);
            piccLogger.info(JsonUtil.toString(logMap));
            JSONObject jsonObject = JsonUtil.parse2JsonObject(ret);
            if("1".equals(jsonObject.getString("subscribe"))){
                return true;
            }
        }catch (Exception e){
            LogUtil.errorLog(e,"");
            return false;
        }
        return false;
    }

    public String getTicket(){
        try{
            String ret = HttpClientUtil.doGet(PICC_GET_TICKET_URL);
            return ret;
        }catch (Exception e){
            LogUtil.errorLog(e,"");
            return "";
        }

    }


    /**
     * 客户满意度有奖调查交互接口
     * @param satisfyQuestion
     * @param prizeList
     * @return
     */
    public boolean sendSatifyQuestion(SatisfyQuestion satisfyQuestion, PrizeList prizeList){
        Map<String,Object> logMap = new HashedMap();
        Map<String,Object> params = new HashedMap();
        String retResult = "",errorMsg = "";
        try{
            params.put("openId",satisfyQuestion.getOpenId());
            params.put("pid",satisfyQuestion.getPid());
            params.put("actName","客户满意度调查");
            params.put("userName",satisfyQuestion.getUserName());
            params.put("phoneNum",satisfyQuestion.getPhoneNum());
            params.put("hasPolicy",satisfyQuestion.getHasPolicy());
            params.put("latestServiceTime",satisfyQuestion.getLatestServiceTime());
            params.put("serviceAgent",satisfyQuestion.getServiceAgent());
            params.put("serviceDetail",satisfyQuestion.getServiceDetail());
            params.put("isSatisfied",satisfyQuestion.getIsSatisfied());
            params.put("rec2Friend",satisfyQuestion.getRec2Friend());
            params.put("scoreReason",satisfyQuestion.getScoreReason());
            params.put("fromChannel",satisfyQuestion.getFromChannel());
            params.put("prize",prizeList.getPrizeId());
            params.put("prizeDetail",prizeList.getPrizeDetail());
            params.put("prizeTime",prizeList.getPrizeDate());
            params.put("zCode",prizeList.getZcode());
            params.put("address",prizeList.getAddress());

            retResult = HttpClientUtil.doPost(PICC_LEARN_HEALTH_URL,params);
        }catch (Exception e){
            LogUtil.errorLog(e,"sendSatifyQuestion error");
            errorMsg = e.getMessage();
            return false;
        }finally {
            logMap.put("errorMsg",errorMsg);
            logMap.put("params",params);
            logMap.put("retResult",retResult);
            piccLogger.info(JsonUtil.toString(logMap));
        }
        return true;

    }

    /**
     * 学点健康知识吧中奖信息交互接口
     * @param satisfyQuestion
     * @param prizeList
     * @return
     */
    public boolean sendLearnHealth(LearnHealth learnHealth, PrizeList prizeList){
        Map<String,Object> logMap = new HashedMap();
        Map<String,Object> params = new HashedMap();
        String retResult = "",errorMsg = "";
        try{
            params.put("openId",learnHealth.getOpenId());
            params.put("actName","学点健康知识吧");
            params.put("userName",prizeList.getUserName());
            params.put("phoneNum",prizeList.getPhoneNum());
            params.put("prize",prizeList.getPrizeId());
            params.put("prizeDetail",prizeList.getPrizeDetail());
            params.put("prizeTime",prizeList.getPrizeDate());

            retResult = HttpClientUtil.doPost(PICC_SATIFY_QUESTION_URL,params);
        }catch (Exception e){
            LogUtil.errorLog(e,"sendLearnHealth error");
            errorMsg = e.getMessage();
            return false;
        }finally {
            logMap.put("errorMsg",errorMsg);
            logMap.put("params",params);
            logMap.put("retResult",retResult);
            piccLogger.info(JsonUtil.toString(logMap));
        }
        return true;

    }

    /**
     * 投保有奖中奖信息交互接口
     * @param satisfyQuestion
     * @param prizeList
     * @return
     */
    public boolean sendInsurance(Insurance insurance, PrizeList prizeList){
        Map<String,Object> logMap = new HashedMap();
        Map<String,Object> params = new HashedMap();
        String retResult = "",errorMsg = "";
        try{
            params.put("pid",insurance.getOpenId());
            params.put("openId",insurance.getOpenId());
            params.put("actName","投保有奖");
            params.put("userName",prizeList.getUserName());
            params.put("phoneNum",prizeList.getPhoneNum());
            params.put("prize",prizeList.getPrizeId());
            params.put("prizeDetail",prizeList.getPrizeDetail());
            params.put("prizeTime",prizeList.getPrizeDate());
            params.put("zCode",prizeList.getZcode());
            params.put("address",prizeList.getAddress());

            retResult = HttpClientUtil.doPost(PICC_INSURANCE_URL,params);
        }catch (Exception e){
            LogUtil.errorLog(e,"sendInsurance error");
            errorMsg = e.getMessage();
            return false;
        }finally {
            logMap.put("errorMsg",errorMsg);
            logMap.put("params",params);
            logMap.put("retResult",retResult);
            piccLogger.info(JsonUtil.toString(logMap));
        }
        return true;

    }

    /**
     * 投保有奖中奖信息交互接口
     * @param satisfyQuestion
     * @param prizeList
     * @return
     */
    public boolean sendPiccMetting(PiccMeeting piccMeeting){
        Map<String,Object> logMap = new HashedMap();
        Map<String,Object> params = new HashedMap();
        String retResult = "",errorMsg = "";
        try{
            params.put("pid",piccMeeting.getPid());
            params.put("openId",piccMeeting.getOpenId());
            params.put("cid",piccMeeting.getCid());
            params.put("message",piccMeeting.getMessage());
            params.put("actName","投保有奖");
            params.put("userName",piccMeeting.getUserName());
            params.put("phoneNum",piccMeeting.getPhoneNum());
            params.put("zCode",piccMeeting.getZcode());
            params.put("address",piccMeeting.getAddress());

            retResult = HttpClientUtil.doPost(PICC_PICC_METTING_URL,params);
        }catch (Exception e){
            LogUtil.errorLog(e,"sendPiccMetting error");
            errorMsg = e.getMessage();
            return false;
        }finally {
            logMap.put("errorMsg",errorMsg);
            logMap.put("params",params);
            logMap.put("retResult",retResult);
            piccLogger.info(JsonUtil.toString(logMap));
        }
        return true;

    }


    public void sendInfo(PrizeList prizeList) {
        int typeId = prizeList.getTypeId();
        int bizId = prizeList.getBizId();

        switch (typeId){
            case 1://1：客户满意度有奖调查
                SatisfyQuestion satisfyQuestion = satisfyQuestionService.fetchById(bizId);
                sendSatifyQuestion(satisfyQuestion,prizeList);
                break;
            case 2://2：学点健康
                LearnHealth learnHealth = learnHealthService.fetchById(bizId);
                sendLearnHealth(learnHealth,prizeList);
                break;
            case 3://3：投保有奖
                Insurance insurance = insuranceService.fetchById(bizId);
                sendInsurance(insurance,prizeList);
                break;
            case 4://4：我和保单有个约会
                break;
        }

    }
}
